import { useEffect, useState } from "react";
import { Modal, Segmented } from "antd";
import { GoToLink, GoToLinkConfig } from "../EventActions/GoToLink";
import { ShowMessage, ShowMessageConfig } from "../EventActions/ShowMessage";
import { CustomJS, CustomJSConfig } from "../EventActions/CustomJs";
import { ComponentMethod, ComponentMethodConfig } from "../EventActions/ComponentMethod";
interface ActionModalProps {
    visible: boolean
    action?: ActionConfig
    handleOk: (config?: ActionConfig) => void
    handleCancel: () => void
}

export type ActionConfig = GoToLinkConfig | ShowMessageConfig | CustomJSConfig | ComponentMethodConfig


export function ActionModal(props: ActionModalProps){
    const { visible, action, handleOk, handleCancel } = props

    const [tab, setTab] = useState('访问链接')
    const [curConfig, setCurConfig] = useState<ActionConfig>()

    const map = {
        goToLink: "访问链接",
        showMessage: "消息提示",
        componentMethod: "组件方法",
        customJs: "自定义 JS"
    }

    // 编辑时，根据 action 的 type 设置 tab
    useEffect(() => {
        if (action?.type) {
            setTab(map[action.type])
            console.log("编辑")
        } else {
            console.log("新增")
        }
    }, [action])

    return ( 
        <Modal
            title="事件动作配置"
            width={800}
            open={visible}
            okText="添加"
            cancelText="取消"
            onOk={() => handleOk(curConfig)}
            onCancel={handleCancel}
        >
            <div className="h-[500px]">
                <Segmented value={tab} onChange={setTab} block options={Object.values(map)}  />
                {
                    tab === '访问链接' && <GoToLink value={action?.type === 'goToLink' ? action.url : undefined} onChange={setCurConfig} />
                }
                {
                    tab === '消息提示' && <ShowMessage value={action?.type === 'showMessage' ? action.config : undefined} onChange={setCurConfig} />
                }
                {
                    tab === '组件方法' && <ComponentMethod value={action?.type === 'componentMethod' ? action.config : undefined} onChange={setCurConfig} />
                }
                {
                    tab === '自定义 JS' && <CustomJS value={action?.type === 'customJs' ? action.code : undefined} onChange={setCurConfig}/>
                }
            </div>
        </Modal>
    )
}